package cn.xqapp.GatewayServer;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.lang3.time.StopWatch;

import java.util.concurrent.atomic.AtomicLong;

public class GatewayServerHandler extends ChannelInboundHandlerAdapter {

    protected StopWatch stopWatch = new StopWatch();
    protected AtomicLong clientConnectionCounter = new AtomicLong();
    protected AtomicLong clientMessageCounter = new AtomicLong();
    protected AtomicLong clientErrorCounter = new AtomicLong();

    public void resetCounter(){
        clientMessageCounter.set(0);
        clientErrorCounter.set(0);

        stopWatch.reset();
        stopWatch.start();
    }

    public long getClientConnectionNum() {
        return clientConnectionCounter.get();
    }

    public long getClientMessageNum() {
        return clientMessageCounter.get();
    }

    public long getClientErrorNum(){
        return clientErrorCounter.get();
    }

    public long getSpanNano(){
        return stopWatch.getNanoTime();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        clientConnectionCounter.incrementAndGet();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        clientConnectionCounter.decrementAndGet();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // System.out.println(String.format("echo message, size %d", ((ByteBuf)msg).readableBytes()));
        ctx.writeAndFlush(msg);
        clientMessageCounter.incrementAndGet();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // cause.printStackTrace();
        ctx.close();
        clientErrorCounter.incrementAndGet();
    }
}
